package 力扣;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZhuYi
 * @create 2025/4/7 19:55
 */
public class 组合总和无重复_LCR081 {
    public static void main(String[] args) {
        int[] candidates = {2, 3, 6, 7};
        int target = 7;
        System.out.println(combinationSum(candidates, target).toString());
    }

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        int start = 0;
        Arrays.sort(candidates);
        backtrack(new ArrayList<Integer>(), candidates, target, 0, res);
        return res;
    }

    static void backtrack(List<Integer> state, int[] candidates, int target, int start, List<List<Integer>> res) {
        if (target == 0) {
            res.add(new ArrayList<Integer>(state));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                break;
            }
            state.add(candidates[i]);
            backtrack(state, candidates, target - candidates[i], i, res);
            state.remove(state.size() - 1);
        }
    }
}
